<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文档解析测试</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            border-radius: 8px;
            padding: 30px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .section {
            margin-bottom: 30px;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background-color: #fafafa;
        }
        .section h2 {
            color: #555;
            margin-top: 0;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #555;
        }
        input[type="file"], input[type="url"] {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        button {
            background-color: #007bff;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        button:hover {
            background-color: #0056b3;
        }
        button:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        .result {
            margin-top: 20px;
            padding: 15px;
            border-radius: 4px;
            max-height: 400px;
            overflow-y: auto;
        }
        .result.success {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        .result.error {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        .loading {
            display: none;
            text-align: center;
            color: #666;
        }
        .content-preview {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            border: 1px solid #e9ecef;
            white-space: pre-wrap;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            line-height: 1.4;
        }
        .meta-info {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 10px;
            margin-bottom: 15px;
        }
        .meta-item {
            background-color: #e9ecef;
            padding: 8px;
            border-radius: 4px;
        }
        .meta-label {
            font-weight: bold;
            color: #495057;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>文档解析 API 测试</h1>
        
        <!-- 文件上传解析 -->
        <div class="section">
            <h2>📄 文件上传解析</h2>
            <div class="form-group">
                <label for="fileInput">选择文档文件:</label>
                <input type="file" id="fileInput" accept=".txt,.md,.html,.htm,.json,.xml,.csv,.pdf,.doc,.docx">
            </div>
            <button onclick="parseFile()">解析文档</button>
            <div class="loading" id="fileLoading">解析中...</div>
            <div id="fileResult"></div>
        </div>
        
        <!-- URL 解析 -->
        <div class="section">
            <h2>🌐 在线文档解析</h2>
            <div class="form-group">
                <label for="urlInput">输入文档URL:</label>
                <input type="url" id="urlInput" placeholder="https://example.com/document.txt">
            </div>
            <button onclick="parseUrl()">解析在线文档</button>
            <div class="loading" id="urlLoading">解析中...</div>
            <div id="urlResult"></div>
        </div>
    </div>

    <script>
        // 解析文件
        async function parseFile() {
            const fileInput = document.getElementById('fileInput');
            const file = fileInput.files[0];
            
            if (!file) {
                showResult('fileResult', false, '请选择一个文件');
                return;
            }
            
            const formData = new FormData();
            formData.append('file', file);
            
            showLoading('fileLoading', true);
            
            try {
                const response = await fetch('/api/documents/parse', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (result.success) {
                    showParseResult('fileResult', result, true);
                } else {
                    showResult('fileResult', false, result.errorMessage || '解析失败');
                }
            } catch (error) {
                showResult('fileResult', false, `请求失败: ${error.message}`);
            } finally {
                showLoading('fileLoading', false);
            }
        }
        
        // 解析URL
        async function parseUrl() {
            const urlInput = document.getElementById('urlInput');
            const url = urlInput.value.trim();
            
            if (!url) {
                showResult('urlResult', false, '请输入URL');
                return;
            }
            
            showLoading('urlLoading', true);
            
            try {
                const response = await fetch('/api/documents/parse/url', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ url: url })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    showParseResult('urlResult', result, true);
                } else {
                    showResult('urlResult', false, result.errorMessage || '解析失败');
                }
            } catch (error) {
                showResult('urlResult', false, `请求失败: ${error.message}`);
            } finally {
                showLoading('urlLoading', false);
            }
        }
        
        // 显示解析结果
        function showParseResult(elementId, result, success) {
            const element = document.getElementById(elementId);
            
            if (success) {
                const metaInfo = `
                    <div class="meta-info">
                        <div class="meta-item">
                            <div class="meta-label">文件名:</div>
                            <div>${result.fileName}</div>
                        </div>
                        <div class="meta-item">
                            <div class="meta-label">文件大小:</div>
                            <div>${formatFileSize(result.fileSize)}</div>
                        </div>
                        <div class="meta-item">
                            <div class="meta-label">文件类型:</div>
                            <div>${result.fileType}</div>
                        </div>
                        <div class="meta-item">
                            <div class="meta-label">内容长度:</div>
                            <div>${result.contentLength} 字符</div>
                        </div>
                        <div class="meta-item">
                            <div class="meta-label">解析时间:</div>
                            <div>${new Date(result.parsedAt).toLocaleString()}</div>
                        </div>
                        ${result.sourceUrl ? `
                        <div class="meta-item">
                            <div class="meta-label">源URL:</div>
                            <div style="word-break: break-all;">${result.sourceUrl}</div>
                        </div>
                        ` : ''}
                    </div>
                `;
                
                const contentPreview = result.content.length > 2000 
                    ? result.content.substring(0, 2000) + '\n\n... (内容已截断，共 ' + result.contentLength + ' 字符)'
                    : result.content;
                
                element.innerHTML = `
                    <div class="result success">
                        <h3>✅ 解析成功</h3>
                        ${metaInfo}
                        <h4>内容预览:</h4>
                        <div class="content-preview">${escapeHtml(contentPreview)}</div>
                    </div>
                `;
            } else {
                showResult(elementId, false, result.errorMessage || '解析失败');
            }
        }
        
        // 显示普通结果
        function showResult(elementId, success, message) {
            const element = document.getElementById(elementId);
            const className = success ? 'success' : 'error';
            const icon = success ? '✅' : '❌';
            
            element.innerHTML = `
                <div class="result ${className}">
                    ${icon} ${message}
                </div>
            `;
        }
        
        // 显示/隐藏加载状态
        function showLoading(elementId, show) {
            const element = document.getElementById(elementId);
            element.style.display = show ? 'block' : 'none';
        }
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
        
        // HTML转义
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    </script>
</body>
</html>
